package com.ycl.javacore.rpctest.remote;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/23
 * Time: 5:35 PM
 * Desc: 类描述
 */
@Data
public class RpcRequest {
    private String interfaceIdentity;
    private Map<String, Object> parameterMap = new HashMap<>();

    private ChannelHandlerContext ctx;
    private String requestId;

    public static RpcRequest parse(String message, ChannelHandlerContext ctx) throws ClassNotFoundException {
        /*
         * {
         *   "interfaces":"interface=com.study.rpc.test.producer.HelloService&method=sayHello&parameter=com.study.rpc.test.producer.TestBean",
         *   "parameter":{
         *      "java.lang.String":"haha",
         *      "com.study.rpc.test.producer.TestBean":{
         *              "name":"小王",
         *              "age":20
         *        }
         *    }
         * }
         */
        JSONObject jsonObject = JSONObject.parseObject(message);
        String interfaces = jsonObject.getString("interfaces");

        JSONObject parameter = jsonObject.getJSONObject("parameter");
        Set<String> strings = parameter.keySet();
        RpcRequest request = new RpcRequest();
        request.setInterfaceIdentity(interfaces);

        Map<String, Object> parameterMap = new HashMap<>();
        String requestId = jsonObject.getString("requestId");
        for (String key : strings) {
            if (key.equals("java.lang.String")) {
                parameterMap.put(key, parameter.getString(key));
            } else {
                Class clazz = Class.forName(key);
                Object object = parameter.getObject(key, clazz);
                parameterMap.put(key, object);
            }
        }
        request.setCtx(ctx);
        request.setRequestId(requestId);
        request.setParameterMap(parameterMap);
        return request;
    }

}
